package com.cloud.lawcase.api.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.lawcase.api.bean.LawCauseSearchCriteria;
import com.cloud.lawcase.api.entity.TcDicLawItem;
import com.cloud.lawcase.api.service.LawItemService;
import com.cloud.lawcase.common.result.QkIcon;
import com.cloud.lawcase.common.result.QkTreeNode;
import com.cloud.lawcase.common.result.Quokka;
import com.cloud.lawcase.common.utils.TreeHelper;

import springfox.documentation.annotations.ApiIgnore;
@ApiIgnore
@RestController
@RequestMapping("lawcase/api/item")
public class LawItemController {

	@Autowired
	private LawItemService lawItemService;

	@RequestMapping("load")
	public Quokka loadLawItems(long id) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<TcDicLawItem> items = lawItemService.loadLawItems(id);
		result.put("items", items);
		result.put("catalog", this.calculateTreeNodes(items));
		return new Quokka(true, result);
	}

	@RequestMapping("analysis")
	public Quokka analysisFile(@RequestParam(value = "file", required = false) MultipartFile file) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<TcDicLawItem> items = lawItemService.analysisFile(file);
		result.put("items", items);
		result.put("catalog", this.calculateTreeNodes(items));
		return new Quokka(true, result);
	}

	@RequestMapping("import")
	public Quokka importLawItem(@RequestBody TcDicLawItem[] lawItems, Long lawId) {
		return new Quokka(true, lawItemService.importLawItem(lawItems, lawId));
	}

	@RequestMapping("search")
	public Quokka searchLawItem(@RequestBody LawCauseSearchCriteria criteria) {
		return new Quokka(true, lawItemService.listLawItemPage(criteria));
	}

	// 计算法规导航树
	private QkTreeNode[] calculateTreeNodes(List<TcDicLawItem> items) {
		List<QkTreeNode> nodes = new ArrayList<QkTreeNode>();
		for (TcDicLawItem item : items) {
			if (!StringUtils.isEmpty(item.getDisplayItemName())) {
				QkTreeNode node = new QkTreeNode();
				String itemCode = new StringBuilder().append(String.format("%02d", item.getChapterId()))
						.append(String.format("%02d", item.getSectionId()))
						.append(String.format("%03d", item.getArticleId()))
						.append(String.format("%02d", item.getParagraphId()))
						.append(String.format("%02d", item.getSubParagraphId()))
						.append(String.format("%02d", item.getEntryId())).toString();
				// 取章节条款项目，去掉后面的0
				node.setId(itemCode.replaceAll("0+$", ""));

				String displayName = item.getDisplayItemName();
				Pattern pattern = Pattern.compile("（([一|二|三|四|五|六|七|八|九|十].*?)）");
				Matcher matcher = pattern.matcher(displayName);
				if (matcher.find()) {
					displayName = "第" + matcher.group(1) + "款";
				}
				node.setLabel(displayName);
				node.setSelectable(true);
				node.setExpanded(true);
				node.setIcon(QkIcon.FA_BOOKMARK);
				int i = item.getItemTypeId();
				if (item.getItemTypeId() == 4) {
					i = 3; // 系统中不存条，条直接是第一款
				}
				String seniorId = itemCode.substring(0, (i - 1) * 2).replaceAll("0+$", "");
				if (StringUtils.isEmpty(seniorId)) {
					node.setRootFlag(true);
				}
				node.setSeniorId(seniorId);
				node.getData().put("itemId", item.getItemId());
				nodes.add(node);
			}
		}
		return TreeHelper.buildList2Tree(nodes);
	}
}
